using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;

namespace PS.Practices.Util
{
    public static class NavigationUtil
    {
        public static void AddWebLinkToParentQuickLaunch(SPWeb web, SPWeb parentWeb)
        {
            SPNavigationNode currentRootNode = CreateHomeNode(web, web.Title); ;
            try
            {
                SPNavigationNodeCollection qLaunch = web.Navigation.QuickLaunch;
                qLaunch.AddAsFirst(currentRootNode);
                SPNavigationNodeCollection parentQLaunch = parentWeb.Navigation.QuickLaunch;

                foreach (SPNavigationNode node in parentQLaunch)
                {
                    qLaunch.AddAsLast(node);
                }
                
                //AddToQuickLaunch(web, parentWeb.Navigation, node2, 0x402);
                //parentWeb.Navigation.AddToQuickLaunch(node2, 0x402);
            }
            catch (SPException)
            {
            }
        }

        public static void AddWebLinkToParentTopNav(SPWeb web, SPWeb parentWeb)
        {
            SPNavigationNodeCollection navCollection = null;
            if (!parentWeb.Navigation.UseShared)
            {
                navCollection = parentWeb.Navigation.TopNavigationBar;
            }
            if (navCollection != null)
            {
                SPNavigationNode node1 = CreateHomeNode(web, web.Title);
                try
                {
                    navCollection.AddAsLast(node1);
                }
                catch (SPException)
                {
                }
            }
        }

        //internal static SPNavigationNode AddToQuickLaunch(SPWeb web, SPNavigation navigation, SPNavigationNode node, int iParentId)
        //{
        //    string text1;
        //    int num1 = web.Request.AddNavigationNode(web.Url, node.Title, node.Url, !node.IsExternal ? 0 : 1, iParentId, -2, true, out text1);
        //    node.Id = num1;
        //    node.LastModified = SPUtility.CreateDateTimeFromSqlString(text1);
        //    node.Navigation = navigation;
        //    return node;
        //}
        
        internal static SPNavigationNode CreateHomeNode(SPWeb web, string strNodeTitle)
        {
            string text1;
            if (web != null)
            {
                if (string.IsNullOrEmpty(strNodeTitle))
                {
                    strNodeTitle = web.Title;
                }
            }
            else
            {
                return null;
            }
            string text2 = web.RootFolder.WelcomePage;
            if (string.IsNullOrEmpty(text2))
            {
                text2 = "default.aspx";
            }
            text1 = web.ServerRelativeUrl + "/" + text2;
            return new SPNavigationNode(strNodeTitle, text1);
        }

    }
}